package org.song.sso.controller;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by JiaLi on 2017-4-9.
 */

@Controller("/cookie")
public class SSOController {

    private static String user = "user";
    private static String pwd = "123";

    @RequestMapping(value = {"/index","/"})
    public String index(Model model, HttpServletRequest request, HttpServletResponse response){
        return checkLogin(model, request, response);
    }

    @RequestMapping(value = {"/user"})
    public String user(Model model, HttpServletRequest request, HttpServletResponse response){
        return checkLogin(model, request, response);
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }


    public String checkLogin(Model model, HttpServletRequest request, HttpServletResponse response){
        // cookie验证是否登录
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("ssocookie") && cookie.getValue().equals("sso")){
                    model.addAttribute("user",user);
                    String url = request.getRequestURI();// /sso/index
                    String page = url.substring(url.lastIndexOf("/")+1);
                    return page;
                }
            }
        }

        // session验证是否登录
        HttpSession session = request.getSession();
        if(session != null){
            if("ssosession".equals(session.getAttribute("ssosession"))){
                model.addAttribute("user",user);
                String url = request.getRequestURI();// /sso/index
                String page = url.substring(url.lastIndexOf("/")+1);
                return page;
            }
        }

        return "login";
    }

    @RequestMapping("/toLogin")
    public String toLogin(Model model,HttpServletRequest request, HttpServletResponse response){
        String user = request.getParameter("user");
        String pwd = request.getParameter("pwd");
        if(this.user.equals(user) && this.pwd.equals(pwd)){

            // 使用session存储
            HttpSession session = request.getSession();
            session.setAttribute("ssosession","ssosession");
            session.setMaxInactiveInterval(10);

            // 使用cookie存储
//            Cookie cookie = new Cookie("ssocookie", "sso");
//            cookie.setPath("/");
//            response.addCookie(cookie);
            model.addAttribute("user",user);
            return "index";
        }
        return "login";
    }
}
